import json
import time

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

from coin.exchange.base.kr_ws.ws_client_base import (WebsocketUpdate)
from coin.exchange.upbit_v1.kr_ws.upbit_parser import UpbitParserManager

#http://www.sahajamit.com/post/capturing-websocket-messages-using-selenium/
#https://stackoverflow.com/questions/27644615/getting-chrome-performance-and-tracing-logs


def _create_driver(symbol):
  caps = DesiredCapabilities.CHROME
  caps['loggingPrefs'] = {'performance': 'ALL'}
  driver = webdriver.Chrome('chromedriver', desired_capabilities=caps)
  driver.implicitly_wait(3)
  driver.get('https://upbit.com')
  driver.implicitly_wait(8)
  driver.get("https://upbit.com/exchange?code=%s" % symbol)
  return driver


def _gen_websocket_received(driver, handler):
  n = 0
  x = None
  try:
    x = driver.get_log("performance")
  except OSError as e:
    # OSError: [Errno 99] Cannot assign requested address
    pass
  if x is None:
    return n

  for entry in x:
    fetched_timestamp = int(time.time() * 10**6) * 1000
    try:
      message_str = entry['message']
      message = json.loads(message_str)
      timestamp = message['message']["params"]["timestamp"]
      method = message['message']["method"]
      if method.lower() == "Network.webSocketFrameReceived".lower():
        payload_str = message['message']['params']['response']['payloadData']
        update = WebsocketUpdate(fetched_timestamp, payload_str)
        handler.on_recv_msg(update)
    except KeyError as e:
      # print("KeyError", e, entry)
      pass
  return n


class UpbitChromeDriver(object):
  def __init__(self, symbol, feed_handler):
    self.driver = _create_driver(symbol)
    self._handler = UpbitParserManager(feed_handler)

  def run(self):
    while True:
      _gen_websocket_received(self.driver, self._handler)
